import { Module } from 'vuex';
import { getUserInfoApi, LoginParam, UserParam } from '/@/api/user';
import { IUserInfo, RootStateTypes } from '../interface/index';
import { loginApi, getMenuListApi } from '/@/api/user';
import router, { routerControl, pathMatch, setCacheTagsViewRoutes } from '/@/router';
import { dynamicRoutes } from '/@/router/route.ts';
import { Session } from '/@/utils/storage';
import { store } from '/@/store/index';

const userModule: Module<IUserInfo, RootStateTypes> = {
	namespaced: true,
	state: {
		token: '',
		name: '',
		avatar: '',
		userInfos: {},
		routerList: [],
	},
	mutations: {
		// 设置token
		getToken(state: any, data: string) {
			state.token = data;
		},
		// 设置用户名
		getName(state: any, data: string) {
			state.name = data;
		},
		// 设置头像
		getAvatar(state: any, data: string) {
			state.avatar = data;
		},
		// 设置用户信息
		getUserInfos(state: any, data: object) {
			state.userInfos = data;
		},
		// 设置路由，菜单中使用到
		getRouterList(state: any, data: Array<object>) {
			state.routerList = data;
		},
	},
	actions: {
		// 登录
		async login({ dispatch }, param: LoginParam) {
			const response = await loginApi(param);
			// 将用户id存起来，用来页面刷新时，获取用户信息传值使用
			Session.set('user_id', response.user_id);
			dispatch('getUserInfo', response);
		},
		// 获取用户信息
		async getUserInfo({ commit, dispatch }, param: UserParam) {
			const response = await getUserInfoApi(param);

			commit('getName', response.userName);
			commit('getAvatar', response.avatar);
			commit('getUserInfos', response);

			dispatch('getMenuList');
		},
		// 获取路由
		async getMenuList({ commit }) {
			// 获取路由
			const response = await getMenuListApi();

			// 是否由前台还是后台控制路由
			const isRequestRoutes = store.state.themeConfig.themeConfig.isRequestRoutes;

			// 添加404页面
			router.addRoute(pathMatch);
			// 后台控制路由
			if (isRequestRoutes) {
				// 后台控制路由，需要将后台返回的meta权限重新赋给本地的路由
				await routerControl(response);
				// 路由存储到vuex
				commit('getRouterList', response);
			} else {
				// 前台控制路由
				// 如果是前台控制路由，直接将前台的路由地址扔给router
				router.addRoute(dynamicRoutes[0]);
				// 将路由整合为一位数组缓存到vuex中，用来在tagsView中过滤
				await setCacheTagsViewRoutes(dynamicRoutes[0].children);
				// 路由存储到vuex
				commit('getRouterList', dynamicRoutes[0].children);
			}

			// 页面刷新时，保证刷新后回到刚才点击展开的页面，而不是每次刷新都回到首页
			const currentPath = Session.get('currentPath');
			if (currentPath) {
				router.push(currentPath);
			} else {
				router.push('/');
			}
		},
	},
};

export default userModule;
